const os = require('os');
const path = require('path');
const fs = require('fs');
const { execSync } = require('child_process');
const { NodeSSH } = require('node-ssh');
const ssh = new NodeSSH();
const readFile = require('util').promisify(fs.readFile);
const buildPath = path.join(__dirname, '/dist');
const buildTarPath = path.join(__dirname, '/build.tar.gz');
if (fs.existsSync(buildTarPath)) {
  fs.unlinkSync(buildTarPath);
}
const command = 'tar -czvf ' + buildTarPath + ' -C ' + buildPath + ' .';

execSync(command);

(async () => {
  const privateKey = path.resolve(os.homedir(), '.ssh/id_ed25519');
  console.log('链接 SSH :' + privateKey);
  fs.access(privateKey, fs.constants.F_OK, (err) => {
    console.log(`${privateKey} ${err ? '不存在' : '存在'}`);
  });

  await ssh.connect({
    host: '121.37.45.254',
    username: 'root',
    port: 22,
    // 私钥文件地址(也可以设置密码，但在GIT里面放密码，不太安全)
    privateKey: await readFile(privateKey, 'utf-8'),
  });
  console.log('删除原先的压缩包');
  await ssh.execCommand('rm -rf /root/build.tar.gz');

  console.log('上传代码包');
  await ssh.putFile(buildTarPath, '/root/build.tar.gz');

  console.log('在服务器上面解压代码包');
  await ssh.execCommand('mkdir /root/build');
  await ssh.execCommand('tar -xzvf /root/build.tar.gz -C /root/build ');

  console.log('删除正在运行的代码');
  await ssh.execCommand('rm -rf /www/dnmp/www/kny_shop_biz_frontend');

  console.log('复制最新代码');
  await ssh.execCommand('mv /root/build /www/dnmp/www/kny_shop_biz_frontend');

  console.log('重启nginx服务');
  await ssh.execCommand('cd /www/dnmp');
  await ssh.execCommand('dc restart nginx');

  console.log('操作完成');
  ssh.dispose();
})();
